/*
 * Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.
 *
 * https://www.mall4j.com/
 *
 * 未经允许，不可做商业用途！
 *
 * 版权所有，侵权必究！
 */
package com.yami.shop.groupbuy.common.listener;

import cn.hutool.core.collection.CollUtil;
import com.yami.shop.bean.event.ProcessActivityProdPriceEvent;
import com.yami.shop.bean.model.Product;
import com.yami.shop.groupbuy.common.dao.GroupActivityMapper;
import com.yami.shop.groupbuy.common.model.GroupActivity;
import lombok.AllArgsConstructor;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 处理活动商品价格的事件
 * @author lhd
 */
@Component("processGroupProdPriceListener")
@AllArgsConstructor
public class ProcessActivityProdPriceListener {

    private final GroupActivityMapper groupActivityMapper;


    @EventListener(ProcessActivityProdPriceEvent.class)
    public void processGroupProdPrice(ProcessActivityProdPriceEvent event) {
        if (CollUtil.isEmpty(event.getProducts())) {
            return;
        }
        List<Long> prodIds = event.getProducts().stream().map(Product::getProdId).collect(Collectors.toList());
        List<GroupActivity> groupActivityList = groupActivityMapper.listActivityPrice(prodIds);
        if (CollUtil.isEmpty(groupActivityList)) {
            return;
        }
        Map<Long, Double> groupProdMap = groupActivityList.stream().collect(Collectors.toMap(GroupActivity::getProdId, GroupActivity::getPrice));
        for (Product product : event.getProducts()) {
            if (!groupProdMap.containsKey(product.getProdId())) {
                continue;
            }
            product.setActivityPrice(groupProdMap.get(product.getProdId()));
        }

//
//
//        List<Product> products = event.getProducts();
//        List<Long> prodIds = new ArrayList<>();
//        products.forEach(product -> prodIds.add(product.getProdId()));
//        List<Product> activityProds = prodMapper.listByProdIds(prodIds);
//        Map<Long, Double> priceMap = activityProds.stream().collect(Collectors.toMap(Product::getProdId, Product::getPrice));
//        for (Product product : products) {
//            Double price = priceMap.get(product.getProdId());
//            product.setActivityPrice(price);
//        }
    }

}
